package com.changgou.handler;

import com.changgou.entity.CustomException;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理类
 */
@ControllerAdvice
public class BaseExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseExceptionHandler.class);

    private static ImmutableMap<Class<? extends Throwable>, Integer> EXCEPTIONS;

    //通过构造器将异常及相关信息存入ImmutableMap中
    public static ImmutableMap.Builder builder = ImmutableMap.builder();

    static {
        builder.put(HttpMessageNotReadableException.class, StatusCode.ERROR);
    }

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result customException(CustomException e) {
        LOGGER.error("catch Exception:{" + e + "}\r\nexception:", e.getMessage(), e);
        return new Result(false, e.getStatusCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result exception(Exception e) {
        LOGGER.error("catch Exception:{" + e + "}\r\nexception:", e.getMessage(), e);
        if (EXCEPTIONS == null) {
            EXCEPTIONS = builder.build();
        }
        Integer statusCode = EXCEPTIONS.get(e);
        if (statusCode == null) {
            return new Result(false, StatusCode.ERROR, e.getMessage());
        }
        return new Result(false, statusCode, e.getMessage());
    }
}
